#include <iostream>
#include <unordered_map>
#include "sock.hpp"
#include "epoll.hpp"
#include "data.hpp"
#include "funtion.hpp"
#define EPOLL_EVENT_NUM 100
#define TIMEOUT 1000
class Epoll_Serve
{
public:
    Epoll_Serve()
    {
        _listen_sock = _serve.SockCreate();
        _fun.SetPort(_listen_sock);
        _fun.Setftl(_listen_sock);
        _serve.Bind();
        _serve.Listen();
        _epoll_model.Ctl(EPOLL_CTL_ADD, _listen_sock, EPOLLIN | EPOLLET);
        Data *ptr = new Data(&_epoll_model);
        ptr->_sptr = &_serve;
        _map.emplace(std::make_pair(_listen_sock, ptr));
    }
    void Start()
    {
        epoll_event event_arr[EPOLL_EVENT_NUM];
        memset(event_arr, 0, EPOLL_EVENT_NUM * sizeof(epoll_event));
        while (true)
        {
            int num = _epoll_model.Wait(event_arr, EPOLL_EVENT_NUM, TIMEOUT);
            switch (num)
            {
            case 0:
                std::cout << "timeout..." << std::endl;
                break;
                std::cout << "epoll_wait fail..." << strerror(errno) << std::endl;
            case -1:
                break;
            default:
                _fun.handle(num, event_arr, _listen_sock, _map);
                break;
            }
        }
    }

public:
    std::unordered_map<int, Data *> _map;

private:
    // 监听套接字
    int _listen_sock;
    // 创建套接字
    Sock _serve;
    // 创建epoll模型
    Epoll _epoll_model;
    // 功能类
    Funtion _fun;
};